package test;


public class LinkedList<E> {

    private Node head;
    private int size;

    class Node{
        E data;
        Node next;
        Node prev;
        Node(E e){
            data=e;
        }

    }
    public boolean add(E e){
        Node node=new Node(e);
        if (node==null){
            head=node;
            head.next=head;
            head.prev=head;
            return true;
        }
        Node last=head.prev;
        last.next=node;
        node.next=head;
        head.prev=node;
        node.prev=last;
        return true;
    }

    @Override
    public String toString() {
       if (head==null){
         return "[]";
       }
       StringBuilder sb=new StringBuilder("[");
       sb.append(head.data);
       Node next=head.next;
       while(next!=head){
           sb.append(","+next.data);
           next=next.next;
       }

        return sb.append("]").toString();
    }
    public int size(){
        return size;
    }
    public E get(int index){
        if (index<0||index>=size){
            throw new IndexOutOfBoundsException("下标越界");
        }
        Node node=head;
        if (index<size>>1){
            for (int i=0;i<index;i++){
               node=node.next;
            }
        }else {
            for (int i=size;i>index;i--){
                node=node.prev;
            }
        }
        return node.data;
    }
}
